#ifndef _GEN_FIGURE_SWF_HPP_
#define _GEN_FIGURE_SWF_HPP_

#include "figure.hpp"
#include "gen_text_swf.hpp"

class figure_swf:public text_swf {
	figure* fig;
	double image_width, image_height;
public:

	// converts to png
	string convert(string input_file){
		string gf=input_file;
		string fl=(fig->name+"-convert.png");

		// FIXME! generalize!
		// $1=output $2=input
		// additionally give information about image on a file (not mandatory)
		if(file_type(gf,"eps")) {
			call_script("convert-eps", fl+" "+gf);
			fig->garbage.push_back(fl);
		} else if(file_type(gf,"pdf")) {
			call_script("convert-pdf", fl+" "+gf);
			fig->garbage.push_back(fl);
		} else if(file_type(gf,"jpg")) {
			call_script("convert-jpg", fl+" "+gf);
			fig->garbage.push_back(fl);
		} else {fl=gf;}
		assert(file_type(fl,"png"), "unsuported figure file tipe", gf);
		assert(file_exist(fl), "failed to convert", gf);
		
		// read info file if exist
		if(file_exist(fl+".info")){
			xml_config_reader fi((fl+".info").c_str());
			if(fi.Exist("info.size.width"))image_width=fi.GetDouble("info.size.width");
			if(fi.Exist("info.size.height"))image_height=fi.GetDouble("info.size.height");
			fig->garbage.push_back(fl+".info");
		}
		return fl;
	}

	virtual double draw(void* draw_param){
		fig=dynamic_cast<figure*>(it);
		SWFSprite* grp=(SWFSprite*) draw_param;
		
		image_width=image_height=-1.0;
		string gf=convert(fig->input_file);

		SWFBitmap *bmp=new SWFBitmap(gf.c_str());
		SWFDisplayItem *di=grp->add(bmp);

		if(image_width<=0.0) image_width=bmp->getWidth();
		if(image_height<=0.0) image_height=bmp->getHeight();
		
		// FIXME! scale=1 is valid. dont change!
		
		if(fig->scalex==0.0){
			if(fig->width!=0.0)fig->scalex=get_width()/image_width;
			else fig->scalex=1.0;
		}

		if(fig->scaley==0.0){
			if(fig->height!=0.0)fig->scaley=get_height()/image_height;
			else fig->scaley=1.0;
		}

		di->scale(fig->scalex,fig->scaley);

		// take only png figure
		set_height(image_height*fig->scaley+get_spacing());
		set_width(image_width*fig->scalex);		
		fig->pinning();
		
		// draw text and add text width to total width
		set_offset(0.0,get_height());
		set_height(get_height()+text_swf::draw(grp)+get_distance());

		return get_height();
	}
	
};


#endif

